import java.util.jar.Attributes.Name;

/**
 * OverrideObject
 * 覆写object类的方法
 * 所有的类都继承自Object,Object类定义了几个重要的方法:
 * toString():把instance输出为String
 * equals():判断两个instance是否逻辑相等
 * hashCode():计算一个instance的哈希值
 * 在需要的时候,我们可以覆写Object的这几个方法
 */
public class OverrideObject {

    public static void main(String[] args) {
        
        PersonOverrideObject p1 = new PersonOverrideObject();
        p1.name = "p1";
        PersonOverrideObject p2 = new PersonOverrideObject();
        p2.name = "p2";

        System.out.println(p1.toString());
        System.out.println(p2.toString());

        System.out.println(p1.equals(p2));

        p2.name = "p1";
        System.out.println(p1.equals(p2));

        p2.name = "p2";
        System.out.println(p1.hashCode());
        System.out.println(p2.hashCode());
    }
}

class PersonOverrideObject {
    public String name;
    
    // 覆写toString方法,输出更有意义的字符串
    @Override
    public String toString() {
        return "Person:name = " + name;
    }

    // 比较两个instance是否相等
    @Override
    public boolean equals(Object obj) {
        // 当且仅当obj为PersonOverrideObject类型
        if (obj instanceof PersonOverrideObject) {
            PersonOverrideObject p = (PersonOverrideObject) obj;
            // 并且name字段相同时,就返回true
            return this.name.equals(p.name);
        }
        return false;
    }

    @Override
    public int hashCode() {
        return this.name.hashCode();
    }
}